package com.bestv.lucene;

import com.bestv.utils.config.GlobalSettings;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.SearcherManager;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

/**
 * Created by Henry on 14-6-11.
 */
public class ProgramSearcherManager {
    private static Logger logger = LoggerFactory.getLogger(ProgramSearcherManager.class);

    private SearcherManager searcherManager;

    private static ProgramSearcherManager instance;

    public static synchronized ProgramSearcherManager getInstance() {
        if (instance == null || instance.getSearcherManager() == null) {
            instance = new ProgramSearcherManager();
        }
        return instance;
    }

    public static void close() {
        try {
            instance.searcherManager.close();
        } catch (IOException e) {
            logger.error("Error on close Lucene Searcher Manager.", e);
        }
    }

    public ProgramSearcherManager() {
        try {
            String indexDir = GlobalSettings.getInstance().getIndexDirectory();
            Directory dir = FSDirectory.open(new File(indexDir));
            searcherManager = new SearcherManager(dir, null);
        } catch (IOException e) {
            logger.error("Error on create Lucene Searcher Manager.", e);
        }
    }

    public IndexSearcher acquire() {
        if (searcherManager == null) return null;
        IndexSearcher searcher = null;
        try {
            searcher = searcherManager.acquire();
        } catch (IOException e) {
            logger.error("Error on create Lucene Searcher.", e);
        }
        return searcher;
    }

    public void release(IndexSearcher searcher) {
        if (searcher == null || searcherManager == null) return;
        try {
            searcherManager.release(searcher);
        } catch (IOException e) {
            logger.error("Error on close Index Searcher.", e);
        }
    }

    public SearcherManager getSearcherManager() {
        return searcherManager;
    }
}
